<template>
  <div class="dragdrop-file-upload">
    <a-upload-dragger
      name="file"
      :showUploadList="false"
      :beforeUpload="beforeUpload"
      :openFileDialogOnClick="false"
    >
    </a-upload-dragger>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
export default {
  props: {
    treeItem: {
      type: Object,
      default: () => {
        return {};
      },
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      fileList: [],
      uploadStatus: 0,
      uploadFileSource: {},
    };
  },
  mounted() {},
  methods: {
    //拖拽上传-上传文件之前钩子
    beforeUpload(file) {
      if (file) {
        this.fileList.push(file);
        this.$message.info("文件上传中，请稍后~");
        this.handleUploadFile(file);
      }
      return false;
    },

    async cutFile(file) {
      let CHUNK_SIZE = 1024 * 1024 * 20;
      let chunkCount = Math.ceil(file.size / CHUNK_SIZE);
      let result = [];
      for (let i = 0; i < chunkCount; i++) {
        let chunk = await this.createChunk(file, i, CHUNK_SIZE);
        result.push(chunk);
      }
      return result;
    },

    createChunk(file, index, chunkSize) {
      return new Promise((resolve) => {
        let start = index * chunkSize;
        let end = start + chunkSize;
        let blob = file.slice(start, end);
        resolve(blob);
      });
    },

    handleUploadFile(file) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          let { statusCode } = res;
          if (statusCode == 200) {
            this.uploadStatus = 1;
            this.uploadFileSource = res;
            this.saveFileData();
          } else {
            this.uploadFileSource = {};
            this.$message.error(res.message ?? "文件上传失败，请稍后重试~");
          }
        })
        .catch((_) => {
          this.$message.error(_.message ?? "文件上传失败，请稍后重试~");
          this.uploadFileSource = {};
        })
        .finally((_) => {});
    },
    saveFileData() {
      let { uploadStatus, treeItem } = this;
      let { dfsFileUuid } = this.uploadFileSource;
      if (uploadStatus == 0) {
        this.$message.warning("文件上传中，请等待~");
        return;
      }
      axios
        .post(
          `/probusiness/bimCadFile/save`,
          {
            classifyId: treeItem.id,
            dfsFileUuid,
            unit: "",
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          let { statusCode, message } = res;
          if (statusCode == 200 && message == "success") {
            this.uploadBlackHole(data);
          } else {
            this.$message.error("上传失败，请稍后重试！");
          }
        })
        .catch((_) => {
          this.$message.error("上传失败，请稍后重试！");
        })
        .finally((_) => {});
    },

    //同步上传到黑洞
    async uploadBlackHole(uuid = "") {
      let { fileList } = this;
      let file = fileList?.[0] ?? "";
      let chunks = await this.cutFile(file);
      let formData = new FormData();
      formData.append("uploadFile", file);
      axios
        .post(`/probusiness/bimCadFile/uploadCadFile?uuid=${uuid}`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          let { statusCode, message, data } = res;
          if (statusCode == 200) {
            let { id } = this.treeItem;
            let proms = [];
            if (data?.FileId) {
              chunks.forEach(async (file, i) => {
                proms.push(() => this.bigFileUpload(file, i, data));
              });
              // 使用Array.reduce()来串联这些Promise
              const promiseChain = proms.reduce(
                (previousPromise, currentFunction) => {
                  return previousPromise.then((result) => {
                    return currentFunction();
                  });
                },
                Promise.resolve()
              );
              promiseChain
                .then((result) => {
                  let { statusCode, message } = result;
                  if (statusCode == 200) {
                    this.$message.success(`上传成功！`);
                    this.resetData();
                    this.$emit("onRefresh", uuid);
                  } else {
                    this.$message.error(message ?? `上传失败，请稍后重试！`);
                  }
                })
                .catch((error) => {
                  this.$message.error(`上传失败，请稍后重试！`);
                })
                .finally((_) => {});
            } else {
              this.$message.success(`上传成功！`);
              this.$emit("onRefresh", uuid);
              this.resetData();
            }
          } else {
            this.$message.error(message ?? `上传失败，请稍后重试！`);
            this.resetData();
          }
        })
        .catch((_) => {
          this.$message.error(`上传失败，请稍后重试！`);
        })
        .finally((_) => {});
    },

    //大文件上传接口
    bigFileUpload(file, i, data) {
      let { FileDatald, FileId, Key } = data;
      let formData = new FormData();
      formData.append("FileId", FileId);
      formData.append("FileInfo", file);
      formData.append("FileDataId", FileDatald);
      formData.append("Key", Key);
      formData.append("BlobIndex", i);
      return new Promise((resolve, reject) => {
        console.log({ FileDatald, FileId, Key, i, file });
        axios
          .post(`/probusiness/bimCadFile/project/cadFile/append`, formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((res) => {
            let {} = res;
            resolve(res);
          })
          .catch((_) => {
            reject();
          });
      });
    },

    resetData() {
      this.fileList = [];
      this.uploadStatus = 0;
      this.uploadFileSource = {};
    },
  },
};
</script>

<style lang="less" scoped>
.dragdrop-file-upload {
  height: 100%;
  width: 100%;
  /deep/.ant-upload-drag {
    background: unset;
    border: 0;
    .ant-upload-btn {
      padding: 0;
    }
  }
}
</style>
